
var user = null;
//3s请求一次新数据
var time = 3000;

var left_top = 0;
var friend_cnt = 11;
var b_height = $("body").height() -30;
var right_top = -$("#content-list").height() + $("#right-content-window").height();
var chatToUserId = null;

var chatQueryHandle = null;

$(document).on('mousewheel DOMMouseScroll', onMouseScroll);


function sendNewMsg() {
    let $input = $("#input-box");
    let msg = $input.val();
    console.log(msg);
    if(msg.length === 0){
        return;
    }
    $input.val("");
    attachMsg(true,msg);


    $.ajax({
        url: 'http://localhost:8080/chatRecord/insertNewMsg',
        async:false,
        method: 'POST',
        crossDomain: true,
        data:{
            userId: user.base.id,
            friendId: chatToUserId,
            msg:msg
        },
        xhrFields: { withCredentials: true },
        success: function (msg) {

        }
    })
}

window.addEventListener("keypress" ,function(e){
    if(e.code === 'Enter'){
        sendNewMsg();
    }
},false)

function getImageFullURLPath(avatar_url) {
    return "http://localhost:8080" + avatar_url;
}

/**
 * 滚动鼠标，模拟列表
 * @param e
 */
function onMouseScroll(e){

    if($("#left-list").hasClass("mouse-enter")){
        left_top += e.originalEvent.wheelDelta;
        if(left_top >0){
            left_top = 0;
        }
        console.log(b_height)
        if(left_top < -(friend_cnt * 80) + b_height){
            left_top = -(friend_cnt * 80) + b_height;
        }
        console.log(left_top)
        $("#left-list-inner").css("top",left_top);
    }

    if($("#right-window").hasClass("mouse-enter")){
        right_top += e.originalEvent.wheelDelta;
        console.log(right_top)
        if(right_top >0){
            right_top = 0;
        }
        let total = -$("#content-list").height() + $("#right-content-window").height();
        if(right_top < total){
            right_top = total;
        }
        $("#content-list").css("top",right_top);

    }
}


/**
 * 登录。。
 */
function checkLogin(){
    console.log("checking login")
    $.post({
        url: 'http://localhost:8080/login/checkLogin',
        async:false,
        method: 'POST',
        crossDomain: true,
        xhrFields: { withCredentials: true },
        success: function (msg) {
            let user = msg.data.user;
            //    user是
            if(user == null){
                layer.msg("请登录");
                window.location.href='../home.html';
            }
            window.user = user;
        }, error: function (error) {
            console.log(error)
        }
    })
}

function loadFriendList() {
   $.ajax({
       url: 'http://localhost:8080/friend/listById',
       async:false,
       method: 'POST',
       crossDomain: true,
       data:{
           uid: user.base.id
       },
       xhrFields: { withCredentials: true },
       success: function (msg) {
           console.log(msg);
           let $left = $("#left-list-inner");
           $left.empty();
           let list = msg.data.list;
           $(list).each(function (i,e){
               console.log(e)
               let str = "<div class='friend-item' value='" + e.friendId + "'";
               str += "onclick='talkTo(" + e.friendId + ")'";
               str += ">";
               str += "<div class='head-pic'>";
               str += "<img src='" + getImageFullURLPath(e.avatarUrl) + "'>";
               str += "</div>";
               str += "<div class='friend-right-info'>" +
                   "<div class='friend-name'>" + e.name +"</div>"+
                   "<div class='sign'>"+ e.signature +"</div>" +
                   "</div>" +
                   "</div>";
                $left.append(str);
                friend_cnt = msg.data.cnt;
                if(friend_cnt < 7){
                    friend_cnt = 7;
                }

           })
       }
   })
}

function loadNewMsg(){

}

/**
 * 加载数据，初始化页面
 */
function loadData(){
    checkLogin();
    if(user === null){
        //没啥意义，只是短路用
        return;
    }
    loadFriendList();

}

function attachMsg(is_my_msg, message) {
    console.log(123)
    console.log(is_my_msg);
    let $content = $("#content-list");
    let str = null;
    if(is_my_msg){
        str = "<div class='my-msg'>" + message + "</div>";
    }else {
        str = "<div class='friend-msg'>" + message + "</div>";
    }
    $content.append(str);
    let total = -$("#content-list").height() + $("#right-content-window").height();
    right_top = total;
    $("#content-list").css("top",right_top);
}

function flushFriendList() {

}

function flushFriendListAndGetNewMsg(){
    console.log(123)

    flushFriendList();
    queryNewMsg();
}

function queryNewMsg() {
    $.ajax({
        url: 'http://localhost:8080/chatRecord/getNewMessage',
        async:true,
        method: 'POST',
        crossDomain: true,
        data:{
            userId: user.base.id,
            friendId:chatToUserId
        },
        xhrFields: { withCredentials: true },
        success: function (msg) {
            let list = msg.data.list;
            console.log(list)
            $(list).each(function (i,e){
                attachMsg(e.senderId1 === user.base.id,e.message);
            })
        }
    });
}

function talkTo(uid){
    chatToUserId = uid;
    let $content = $("#content-list");
    $content.empty();
    $.ajax({
        url: 'http://localhost:8080/chatRecord/listByUserId',
        async:true,
        method: 'POST',
        crossDomain: true,
        data:{
            userId: user.base.id,
            friendId: uid
        },
        xhrFields: { withCredentials: true },
        success: function (msg) {
            console.log(msg);
            $(msg.data.list).each(function (i,e){
                console.log("si1 = " + e.senderId1 + "my is " + user.base.id);
                attachMsg(e.senderId1 === user.base.id,e.message);
            })
            $("#right-window").css("display","initial");
            if(chatQueryHandle !== null){
                window.clearInterval(chatQueryHandle);
            }

            chatQueryHandle = window.setInterval(flushFriendListAndGetNewMsg,time);
        }
    })

}

